package com.fzfnn.scrapbook.mapper;

import com.fzfnn.scrapbook.entity.Journal;
import com.fzfnn.scrapbook.vo.JournalVo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface JournalLikeMapper {

    @Insert("INSERT INTO journal_like(journal_id, user_id) VALUES(#{journalId}, #{userId})")
    int insertLike(@Param("journalId") int journalId, @Param("userId") int userId);

    @Delete("DELETE FROM journal_like WHERE journal_id = #{journalId} AND user_id = #{userId}")
    int deleteLike(@Param("journalId") int journalId, @Param("userId") int userId);

    @Select("SELECT COUNT(*) FROM journal_like WHERE journal_id = #{journalId}")
    int countLikes(@Param("journalId") int journalId);

    @Select("SELECT COUNT(*) FROM journal_like WHERE journal_id = #{journalId} AND user_id = #{userId}")
    int isLiked(@Param("journalId") int journalId, @Param("userId") int userId);

    @Update("UPDATE journal SET like_count = like_count + 1 WHERE journal_id = #{journalId}")
    void incrementLikeCount(@Param("journalId") int journalId);

    @Update("UPDATE journal SET like_count = like_count - 1 WHERE journal_id = #{journalId} AND like_count > 0")
    void decrementLikeCount(@Param("journalId") int journalId);

    @Select("SELECT * FROM journal WHERE journal_id = #{journalId}")
    Journal selectById(@Param("journalId") int journalId);

    @Select("SELECT user_id FROM journal_like WHERE journal_id = #{journalId}")
    List<Integer> selectLikedUsers(@Param("journalId") int journalId);

    @Select("SELECT \n" +
            "  j.journal_id AS journalId,\n" +
            "  j.title,\n" +
            "  j.content,\n" +
            "  j.img_url AS imgurl,\n" +
            "  j.tag,\n" +
            "  j.created_at AS createdAt,\n" +
            "  j.updated_at AS updatedAt,\n" +
            "  j.like_count,\n" +
            "  j.user_id AS userId,\n" +
            "  u.username AS username,\n" +
            "  u.imgurl AS avatarUrl ," +
            "  l.liked_at AS likedAt\n" +
            "FROM journal_like l\n" +
            "JOIN journal j ON l.journal_id = j.journal_id\n" +
            "JOIN user u ON j.user_id = u.user_id\n" +
            "WHERE l.user_id = #{userId}\n" +
            "ORDER BY l.liked_at DESC;\n")
    List<JournalVo> getLikedJournalsByUserId(@Param("userId") int userId);

}
